package com.android.lovely.admob

import android.os.SystemClock
import android.text.format.DateUtils
import com.android.lovely.manager.WorkStore
import com.android.lovely.user.UserManager
import com.google.android.gms.ads.rewarded.RewardedAd
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import com.kotlin.extensions.coroutine.applicationScope
import kotlinx.coroutines.Job

sealed class Ad(var ad: RewardedAd? = null, var time: Long = SystemClock.elapsedRealtime()) {

    data object DailySign : Ad()
    data object WalletPage : Ad()
    data object WalletDialog : Ad()
    data object Chat : Ad()

    var job: Job? = null

    fun hasCache(): Boolean {
        if (SystemClock.elapsedRealtime() - time > 50 * DateUtils.MINUTE_IN_MILLIS) {
            ad = null
            return false
        }
        return ad != null
    }

    fun enable(): Boolean {
        return when (this) {
            WalletDialog -> getId().isNotEmpty() && WorkStore.getInstance().buyDialogShowCount < (UserManager.userInfo?.adNormalMaxNum ?: 5)
            WalletPage -> getId().isNotEmpty() && WorkStore.getInstance().buyPageShowCount < (UserManager.userInfo?.adBuyPageMaxNum ?: 5)
            else -> getId().isNotEmpty()
        }
    }

    fun getId(): String {
        return when (this) {
            Chat -> WorkStore.getInstance().lovelyAdId?.chat.orEmpty()
            DailySign -> WorkStore.getInstance().lovelyAdId?.signIn.orEmpty()
            WalletDialog -> WorkStore.getInstance().lovelyAdId?.normal.orEmpty()
            WalletPage -> WorkStore.getInstance().lovelyAdId?.buy.orEmpty()
        }
    }

    fun getCache(): RewardedAd? {
        if (hasCache()) {
            val cache = ad
            ad = null
            return cache
        }
        return null
    }

    fun load(): Job? {
        if (enable().not()) {
            return null
        }

        if (hasCache()) {
            return null
        }
        if (job?.isActive == true) {
            return job
        }

        return applicationScope.launchSafety {
            loadReward(getId()).let { loadResult ->
                var result = loadResult
                if (loadResult == null && this@Ad == DailySign) {
                    result = loadReward(getId())
                }
                if (result != null) {
                    ad = result
                    time = SystemClock.elapsedRealtime()
                }
            }
        }.also {
            job = it
        }
    }
}